package com.vieewer.btdemo.view.microsoft.audio;


import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.squareup.okhttp.*;
import org.jetbrains.annotations.Nullable;

import java.io.IOException;
import java.util.Collections;

public class TranslateHelper {

    private static String subscriptionKey = "4ecdd72c20754ccc8e41a188b2c84c09";
    private static String endpoint = "https://api.cognitive.microsofttranslator.com/";
    private OkHttpClient client;
    private String code = "zh-Hans";
    String url = endpoint + "/translate?api-version=3.0&to=" + code;

    //String url = "https://vieewertranstxt.cognitiveservices.azure.com/sts/v1.0/issuetoken" + "/translate?api-version=3.0&to=zh-Hans";

    public TranslateHelper() {
        client = new OkHttpClient();
        client.setProtocols(Collections.singletonList(Protocol.HTTP_1_1));
    }

    public void setLanguageCode(@Nullable String targetLanguage) {
        code = targetLanguage;
    }

    // This function performs a POST request.
    //生成 POST 请求。 可随意更改用于翻译的文本。 文本必须进行转义。
    public String Post(String content) throws IOException {
        url = endpoint + "/translate?api-version=3.0&to=" + code;

        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, content);
        Request request = new Request.Builder()
                .url(url).post(body)
                .addHeader("Ocp-Apim-Subscription-Key", subscriptionKey)
                .addHeader("Content-type", "application/json").build();
        Response response = client.newCall(request).execute();
        return response.body().string();
    }


    // This function prettifies the json response.
    //这个简单的函数分析来自文本翻译服务的 JSON 响应并对其进行美化。
    public static String prettify(String json_text) {
        JsonParser parser = new JsonParser();
        JsonElement json = parser.parse(json_text);
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        return gson.toJson(json);
    }


}
